package com.base.xm.fingerprintdemo.utils;

import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import android.support.annotation.RequiresApi;

import java.security.KeyStore;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;

/**
 * 密钥工具类
 */
public class LocalAndroidKeyStore {
    //密钥库
    private KeyStore mStore;
    //密钥名称
    public static final String KEY_NAME = "key";
    //密钥类型
    public static final String KEY_TYPE = "AndroidKeyStore";

    @RequiresApi(api = Build.VERSION_CODES.M)
    public LocalAndroidKeyStore() {
        try {
            mStore = KeyStore.getInstance(KEY_TYPE);
            generateKey();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成密钥
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void generateKey() {
        try {
            KeyGenerator generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, KEY_TYPE);
            mStore.load(null);
            int purpose = KeyProperties.PURPOSE_DECRYPT | KeyProperties.PURPOSE_ENCRYPT;
            KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(KEY_NAME, purpose);
            builder.setUserAuthenticationRequired(true);
            builder.setBlockModes(KeyProperties.BLOCK_MODE_CBC);
            builder.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7);
            generator.init(builder.build());
            generator.generateKey();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取加密对象
     *
     * @param purpose
     * @param IV
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public FingerprintManager.CryptoObject getCryptoObject(int purpose, byte[] IV) {
        try {
            mStore.load(null);
            SecretKey key = (SecretKey) mStore.getKey(KEY_NAME, null);
            Cipher cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC
                    + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7);
            if (purpose == KeyProperties.PURPOSE_ENCRYPT) {
                cipher.init(Cipher.ENCRYPT_MODE, key);
            } else {
                cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(IV));
            }
            return new FingerprintManager.CryptoObject(cipher);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
